package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xrit.sunnyday.dao.SetmealDao;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.pojo.Setmeal;
import com.xrit.sunnyday.service.SetmealService;
import com.xrit.sunnyday.utils.QiNiuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    //分页查询
    @Override
    public PageInfo<Setmeal> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%");
        }
        List<Setmeal> setmealList = setmealDao.findPageBySetmeal(queryPageBean.getQueryString());
        return new PageInfo<>(setmealList);
    }

    //删除
    @Override
    public void deleteById(Integer id) {
        //删除中间表
        setmealDao.deleteSetmealandCheckGroup(id);
        //删除套餐表
        setmealDao.deleteById(id);
    }

    //查询所有
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    //封装FreeMarker工具类
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;      //注入FreeMarker配置类
    @Value("${out_put_path}")
    private String out_put_path;                    //引入FreeMarker配置类中的输出路径
    /**
     * 封装生成静态页面的方法
     */
    private void generateHtml(String templateName, Map<String,Object> dataMap,String outFileName){
        //1.获取FreeMarker配置类
        Configuration configuration = freeMarkerConfig.getConfiguration();
        BufferedWriter writer = null;
        try {
            //2.加载模板文件  -->已有，参数传进来
            Template template = configuration.getTemplate(templateName);
            //3.构建数据     -->已有，参数传进来
            //4.输出文件路径  -->文件名称已有，参数传进来
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileName),"UTF-8"));
            //5.将数据填充到模板
            template.process(dataMap,writer);
            //6.刷新缓冲流
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //7.关流
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    @Transactional
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (null != checkgroupIds) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealCheckGroup(setmeal.getId(), checkgroupId);
            }
        }
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }
    //b.生成套餐列表、套餐具体详情静态页面
    private void generateMobileStaticHtml() {
        try {
            //1.套餐列表静态页面
            generateSetmealListHtml();
            //2.套餐详情静态页面生成单个就行了，为了测试方便，生成所有的
            generateSetmealDetailHtml();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //b.1生成套餐静态页面
    private void generateSetmealListHtml() {
        //1.准备模板文件路径,freemarker配置文件中已经配置好了路径前缀
        String templateName = "mobile_setmeal.ftl";
        //2.准备套餐列表页面的数据
        List<Setmeal> setmealList = setmealDao.findAll();
        //2.1.拼图片路径返回
        setmealList.forEach(setmeal -> {
            setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
        });
        //3.构建数据
        Map<String,Object> dataMap = new HashMap<String,Object>();
        //注意，key值一定要与模板文件中的变量保持一致
        dataMap.put("setmealList",setmealList);
        //4.输出全路径
        String setmealListFile = out_put_path+"mobile_setmeal.html";
        //调用封装的页面生成方法
        generateHtml(templateName,dataMap,setmealListFile);
    }
    //b.2生成套餐详情静态页面
    private void generateSetmealDetailHtml() {
        //1.准备模板文件路径,freemarker配置文件中已经配置好了路径前缀
        String templateName = "mobile_setmeal_detail.ftl";
        //2.准备数据：把所有套餐都生成详情页面,方便测试
        List<Setmeal> setmealList = setmealDao.findAll();
        //2.1setmealList中的套餐是没有详情信息，即没有检查组也没有检查项的信息，要查询一遍
        for (Setmeal setmeal : setmealList) {
            //2.2.获取套餐详情
            Setmeal setmealDetail = setmealDao.findDetailById(setmeal.getId());
            //2.3设置套餐的图片路径
            setmealDetail.setImg(QiNiuUtils.DOMAIN + setmealDetail.getImg());
            //3.构建数据
            Map<String, Object> dataMap = new HashMap<String,Object>();
            dataMap.put("setmeal", setmealDetail);
            //4.输出全路径
            String setmealListFile = out_put_path+"mobile_setmeal_" + setmealDetail.getId() + ".html";
            //调用封装的页面生成方法
            generateHtml(templateName,dataMap,setmealListFile);
        }
    }

    //根据id查询
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    //查询套餐和检查组
    @Override
    public List<Integer> findSetmealIdAndCheckGroupId(Integer id) {
        return setmealDao.findSetmealIdAndCheckGroupId(id);
    }

    //修改
    @Override
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.update(setmeal);
        setmealDao.deleteSetmealandCheckGroup(setmeal.getId());
        if (null != checkgroupIds) {
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addSetmealCheckGroup(setmeal.getId(), checkgroupId);
            }
        }
    }

    /**
     * 查出数据库中的所有图片
     *
     * @return
     */
    @Override
    public List<String> findImgs() {
        return setmealDao.findImgs();
    }

    //根据id查询套餐详情
    @Override
    public Setmeal findDetailById(Integer id) {
        return setmealDao.findDetailById(id);
    }

//    套餐预约订单百分比
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }


}
